/**
 * DishService
 *
 * @project sky-take-out_1
 * @author MECHREVO
 * @date 2023/12/5 14:15:39
 * @version 1.0
 */
package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishExitsException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {
    private final DishMapper dishMapper;
    private final DishFlavorMapper dishFlavorMapper;
    private final SetmealMapper setmealMapper;
    private final RedisTemplate<String, String> redisTemplate;

    @Override
    @Transactional
    public void Create(DishDTO dishDTO) {
        Dish dishQuery = new Dish();
        dishQuery.setName(dishDTO.getName());
        Integer countByName = dishMapper.selectCount(dishQuery);
        if (countByName > 0) {
            throw new DishExitsException(MessageConstant.DISH_EXITS);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insert(dish);
        saveDishFlavors(dishDTO, dish);
      //todo 缓存
        //清除缓存
        String key = getKey(dish);
        redisTemplate.delete(key);
    }


    /**
     * 分页查询
     *
     * @param dishPageQueryDTO
     */
    @Override
    public PageResult<DishVO> page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Dish dishQuery = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO, dishQuery);
        List<Dish> dish = dishMapper.page(dishQuery);
        List<DishVO> dishVOList = dish.stream().map(item -> {
                    DishVO dishVO = new DishVO();
                    BeanUtils.copyProperties(item, dishVO);
                    return dishVO;
                })
                .collect(java.util.stream.Collectors.toList());
        Page<Dish> p = (Page<Dish>) dish;
        PageResult<DishVO> pageResult = new PageResult<>(p.getTotal(), dishVOList);
        return pageResult;
    }

    @Override
    public void delete(List<String> ids) {
        Integer countByIdsAndStatus = dishMapper.selectByIdsAndStatus(ids, StatusConstant.ENABLE);
        if (countByIdsAndStatus > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        Integer countBySetmeal = setmealMapper.selectCountByDishIds(ids);
        if (countBySetmeal > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishMapper.deleteById(ids);
        //清除缓存
        Set<String> keys = redisTemplate.keys("Dish:*");
        redisTemplate.delete(keys);
    }

    @Override
    public DishVO infoById(Long id) {
        Dish dish = dishMapper.selectById(id);
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    @Override
    @Transactional
    public void modify(DishDTO dishDTO) {
        Dish dishQuery = new Dish();
        dishQuery.setName(dishDTO.getName());
        dishQuery.setId(dishDTO.getId());
        Integer countByName = dishMapper.selectCount(dishQuery);
        if (countByName > 0) {
            throw new DishExitsException(MessageConstant.DISH_EXITS);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        saveDishFlavors(dishDTO, dish);
        //清除缓存
        String key = getKey(dish);
        redisTemplate.delete(key);
    }

    @Override
    public List<DishVO> selectdish(Dish dish) {
        String key = getKey(dish);
        String dishJson = redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(dishJson)){
            return  JSON.parseArray(dishJson,DishVO.class);
        }
        List<Dish> dishList = dishMapper.page(dish);
        List<DishVO> list = new ArrayList<>();
        for (Dish dish1 : dishList) {
            DishVO dishVO1 = new DishVO();
            BeanUtils.copyProperties(dish1, dishVO1);
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(dish1.getId());
            dishVO1.setFlavors(dishFlavors);
            list.add(dishVO1);
        }
        if(Objects.nonNull(list)&& !list.isEmpty()){
        redisTemplate.opsForValue().set(key,JSON.toJSONString(list));
        }
        return list;
    }
//获取key
    private String getKey(Dish dish) {
        String key="Dish:"+ dish.getCategoryId();
        return key;
    }

    @Override
    public List<DishVO> list(Integer type) {
        List<DishVO> dishVO = dishMapper.list(type);
        return dishVO;
    }

    /**
     * 保存菜品和菜品的组合
     *
     * @param dishDTO
     * @param dish
     */
    private void saveDishFlavors(DishDTO dishDTO, Dish dish) {
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(item -> item.setDishId(dish.getId()));
            dishFlavorMapper.create(flavors);
        }
    }
}
